package com.henu.tanhang;

import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiSortType;
import com.henu.R;
import com.henu.tanhang.entity.Detail;
import com.henu.tanhang.manager.LocationManager;
import com.henu.tanhang.poisearch.PoiSearchManager;

import java.util.ArrayList;

public class Map extends AppCompatActivity implements SensorEventListener {

    private AutoCompleteTextView keyWorldsView;
    private MapView mapView;
    public BaiduMap baiduMap;
    private EditText searchlist;
    private MyLocationData locationData;
    int searchType = 0;
    private Double lastX = 0.0;
    private ImageButton mycollect_return;
    private SensorManager sensorManager;
    private int mCurrentDirection = 0;
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private float mCurrentAccracy;
    private int loadIndex = 0;
    private Button location;
    private Button searchall;
    Handler handler;
    private PoiSearchManager poiSearchManager;
    private ArrayList<Detail> list = new ArrayList<>();


    //曾宪梓楼纬度34.81962,经度114.31277

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        LocationManager.getInstance(null).startLocationSDK();
        poiSearchManager = new PoiSearchManager(this);
        poiSearchManager.init(new PoiSearchManager.MyListerner() {
            @Override
            public void callBack(PoiInfo info) {
                //Toast.makeText(Map.this, "aaaaaaaaaaa", Toast.LENGTH_SHORT).show();
                Detail detail=new Detail();
                detail.setCheckname(info.name);
                detail.setAddress(info.address);
                detail.setPhone(info.phoneNum);
                list.add(detail);
            }
        });
        searchall = (Button)findViewById(R.id.searchall);
        searchall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Map.this,CheakAll.class);
                intent.putExtra("detail",list);
/*                Intent intent1  = new Intent(Map.this,DetailActivity.class);
                intent1.putExtra("detail",list);*/
                startActivity(intent);
            }
        });
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务
        keyWorldsView = (AutoCompleteTextView) findViewById(R.id.searchkey);
        keyWorldsView.setThreshold(1);

        mycollect_return = (ImageButton)findViewById(R.id.mycollect_return) ;
        mapView = (MapView) findViewById(R.id.bmapview);
        baiduMap = mapView.getMap();
        location = (Button) findViewById(R.id.location);

        mycollect_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    locationData = (MyLocationData) msg.obj;
                    mCurrentAccracy = locationData.accuracy;
                    mCurrentLat = locationData.latitude;
                    mCurrentLon = locationData.longitude;
                    baiduMap.setMyLocationEnabled(true);
                    baiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                            MyLocationConfiguration.LocationMode.NORMAL, true, null));

                    baiduMap.setMyLocationData(locationData);

                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.target(new LatLng(locationData.latitude, locationData.longitude)).zoom(17.5f);
                    baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                } else {
                    Toast.makeText(getBaseContext(), "获取定位失败！", Toast.LENGTH_SHORT).show();
                }
            }
        };
        location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LocationManager.getInstance(null).requestLocation(handler);
            }
        });

        keyWorldsView.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() <= 0) {
                    return;
                }
                /**
                 * 使用建议搜索服务获取建议列表，结果在onSuggestionResult()中更新
                 */
                poiSearchManager.requestSuggest(charSequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
    }

    @Override
    protected void onPause() {
        mapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        Log.i("TAG", "resume");
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_UI);
        LocationManager.getInstance(null).startLocationSDK();
        mapView.onResume();
        super.onResume();
    }

    @Override
    protected void onStop() {
        // LocationManager.getInstance(null).stopLocationSDK();
        sensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        mapView.onDestroy();
        super.onDestroy();
    }

    //响应周边搜索按钮点击事件
    public void searchNearbyProcess(View v) {
        searchType = 2;
        searchlist = (EditText)findViewById(R.id.searchlist);
        try {
            if (locationData == null) {
                Toast.makeText(getBaseContext(), "请先定位！", Toast.LENGTH_LONG).show();
            } else if(searchlist == null){
                Toast.makeText(getBaseContext(),"请输入搜索范围！",Toast.LENGTH_LONG).show();
            }else {
                LatLng center = new LatLng(locationData.latitude, locationData.longitude);
                int radius =Integer.parseInt(searchlist.getText().toString().trim());
                PoiNearbySearchOption nearbySearchOption = new PoiNearbySearchOption().keyword(keyWorldsView.getText()
                        .toString()).sortType(PoiSortType.distance_from_near_to_far).location(center)
                        .radius(radius).pageNum(loadIndex);
                list.clear();
                poiSearchManager.search(nearbySearchOption,baiduMap,locationData,radius);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            MyLocationData locationData = new MyLocationData.Builder()
                    .accuracy(mCurrentAccracy)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(mCurrentLat)
                    .longitude(mCurrentLon).build();
            baiduMap.setMyLocationData(locationData);
        }
        lastX = x;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }
}

